<?php
// +----------------------------------------------------------------------
// | quickadmin框架 [ quickadmin框架 ]
// +----------------------------------------------------------------------
// | 版权所有 2020~2022 南京新思汇网络科技有限公司
// +----------------------------------------------------------------------
// | 官方网站: https://www.quickadmin.top
// +----------------------------------------------------------------------
// | Author: zs <909883663@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\Site;
use app\BaseController;
use app\dic\DicOrder;
use app\dic\DicProduct;
use app\dic\DicPublic;
use app\dic\DicSite;
use app\dic\OrderDic;
use think\App;
use think\facade\Db;
use util\Excel;
use think\cache\driver\Redis;

use util\Token;
/*
 * @Description: index
 * @Date: 2021-05-25 14:57:43
 */

class Index extends BaseController
{

    protected $model = null;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new Site();
    }


    // 首页

    public function index()
    {

        // halt(phpinfo());
        //mock数据


        $data = [
            'a' => ['c' => 1, 'b' => 2],
            'b1' => 2,
            'c1' => 2,
            'd1' => 2,
            'e1' => 2,
            'f1' => 2,
            'h1' => 2,
            'i1' => 2,
            'j1' => 2,
            'k1' => 2,
            'l1' => 2,
            'm1' => 2,
            'n1' => 2,
            'o1' => 2,
            'p1' => 2,
            'q1' => 2,
            'r1' => 2,
            's1' => 2,
            't1' => 2,
            'u1' => 2,
            'v1' => 2,
            'w1' => 2,
            'x1' => 2,
            'y1' => 2,
            'z1' => 2,

        ];

        $res = mgtable('ceshi')->insert($data);
        halt($res);
        return json($data);
    }



    /**
     * 店铺数据迁移
     */
    public function sitetransfer()
    {
        //迁移shopify店铺
        $rst =  table('fedition_accounturl')->where(['info' => 'shopify'])->select()->toarray();
        foreach ($rst as $v) {
            $rst_new[] = [
                'site_name' => $v['name'],
                'site_url' => $v['shopifyname'],
                'site_type' => DicSite::$site_type_1,
                'status' => $v['status'],
                'currency' => $v['currency'],
                'apikey' => $v['shopifyapikey'],
                'apisecret' => $v['shopifysecretapikey'],
                'add_time' => date('Y-m-d H:i:s', $v['createtime']),
                'update_time' => date('Y-m-d H:i:s', $v['updatetime']),
                'adminid' => 1
            ];
        }
        table('site')->insertAll($rst_new);
        return '数据转入成功';
    }


    /**
     * 通过商品id获取单个产品信息
     */

    public function  get_product_product_id()
    {
        $site_id = input('site_id');
        $product_id = input('product_id');
        $site = table('site')->where(['id' => $site_id])->find();
        $url = $site['site_url'] . DicProduct::$product_url . '/' . $product_id . '.json';
        //取出单个商品
        $product = geturl($url, $site['apikey'], $site['apisecret']);
        $product = json_decode($product, true);
        halt($product);
        $product = $product['product'];
        halt($product);
    }



    // 搬数据
    public function ban()
    {
        $data = Excel::import('storage/bra10.xls');
        unset($data[1], $data[2]);
        foreach ($data as  $value) {
            table('sumskucount')->where(['sku' => strtolower($value[0])])->update(['sum' => $value[3]]);
        }
        return success('更新成功');
    }


    /**
     * 通过商品id获取元字段信息
     */

    public function  get_metafield_product_id()
    {
        // $str = 'bra' . DicPublic::$encryption_str;
        // halt(explode(DicPublic::$encryption_str, $str));
        $site_id = input('site_id');
        $product_id = input('product_id');
        $site = table('site')->where(['id' => $site_id])->find();
        $url = $site['site_url'] . DicProduct::$product_url . '/' . $product_id . '/metafields.json';
        $metafield = geturl($url, $site['apikey'], $site['apisecret']);
        $metafield = json_decode($metafield, true);
        // halt($metafield['metafields']);
        if (isset($metafield['metafields'])) {
            halt(array_column($metafield['metafields'], 'value', 'key'));
        }
        return [];
    }

    //生成sku
    public function get_sku()
    {
        $product_id =  input('product_id') ? input('product_id') : 7969504854235;
        $brand = table('brand')->where(['product_id' => $product_id])->find();
        if (!isset($brand['title'])) {
            $brand['title'] = '';
        }
        $color = table('color')->field('id,title')->select()->toarray();
        $color = array_column($color, 'title');
        asort($color);
        $color = array_values($color);
        $size = table('size')->field('title')->select()->toarray();
        $size =  array_column($size, 'title');
        asort($size);
        $size_info = array_values($size);
        $cup = table('cup')->field('title')->select()->toarray();
        $cup =  array_column($cup, 'title');
        asort($cup);
        $cup_info = array_values($cup);
        $excel = table('demo_excel')->field('id,title')->select()->toarray();
        $sku_table = table('sku_table')->where(['product_id' => $product_id])->find();
        $colors = '';
        $sizecup = '';
        $quantity = '';
        $table_cup = '';
        $table_size = '';
        $switch = 0;
        $remove_sku = array();
        if (!empty($sku_table)) {
            if ($sku_table['color']) {
                $colors = json_decode($sku_table['color']);
            }
            if ($sku_table['cup']) {
                $table_cup = json_decode($sku_table['cup']);
            }
            if ($sku_table['size']) {
                $table_size = json_decode($sku_table['size']);
            }
            if ($sku_table['excel']) {
                $sizecup = (int)$sku_table['excel'];
            }
            if ($sku_table['quantity']) {
                $quantity = (int)$sku_table['quantity'];
            }
            if ($sku_table['switch']) {
                $switch = (int)$sku_table['switch'];
            }
            if ($sku_table['sku']) {
                $sku_table['sku'] = json_decode($sku_table['sku']);
            }
            if ($sku_table['sku_name']) {
                $sku_table['sku_name'] = json_decode($sku_table['sku_name']);
            }
            if ($sku_table['option1']) {
                $sku_table['option1'] = json_decode($sku_table['option1']);
            }
            if ($sku_table['option2']) {
                $sku_table['option2'] = json_decode($sku_table['option2']);
            }
            if ($sku_table['option3']) {
                $sku_table['option3'] = json_decode($sku_table['option3']);
            }

            if ($sku_table['remove_sku']) {
                $sku_table['remove_sku'] = json_decode($sku_table['remove_sku']);
                for ($i = 0; $i < count($sku_table['remove_sku']); $i++) {
                    $remove_sku[$i]['name'] = $sku_table['remove_sku'][$i];
                }
            }
            $sku_table['tableData'] = array();
            if (!empty($sku_table['sku']) && !empty($sku_table['sku_name'])) {
                for ($i = 0; $i < count($sku_table['sku']); $i++) {
                    $sku_table['tableData'][$i]['sku'] = $sku_table['sku'][$i] ? $sku_table['sku'][$i] : '';
                    $sku_table['tableData'][$i]['name'] = $sku_table['sku_name'][$i] ? $sku_table['sku_name'][$i] : '';
                    $sku_table['tableData'][$i]['option1'] = $sku_table['option1'][$i] ? $sku_table['option1'][$i] : '';
                    $sku_table['tableData'][$i]['option2'] = $sku_table['option2'][$i] ? $sku_table['option2'][$i] : '';
                    $sku_table['tableData'][$i]['option3'] = $sku_table['option3'][$i] ? $sku_table['option3'][$i] : '';
                }
            }
        }
        $arr = [
            'brand_title' => $brand['title'],

            'color' =>  $color,
            'colors' => $colors,
            'size' => $table_size,
            'sizes' => $size_info,
            'cup' => $table_cup,
            'cups' => $cup_info,

            'product_id' => $product_id,
            'excel' => $excel,
            'sku_table' => $sku_table,
            'sizecup' => $sizecup,
            'quantity' => $quantity,
            'switch' => $switch,
            'remove_sku' => $remove_sku,
        ];
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $arr,
        ];
        return json($data);
    }

    //尺码映射
    public function get_excel()
    {
        $option1 = input('option1');
        $option1 = json_decode($option1, true);
        $option2 = input('option2');
        $option2 = json_decode($option2, true);
        $option3 = input('option3');
        $option3 = json_decode($option3, true);
        $sku_name = input('sku_name');
        $sku_name = json_decode($sku_name, true);

        $sku_data = input('sku_data');
        $sku_data = json_decode($sku_data, true);;
        $excel_id = input('excel_id') ? input('excel_id') : 0;
        $brand = input('brand') ? input('brand') : 1;
        $quantity = input('quantity') ? input('quantity') : 1;
        $excel_data = table('demo_excel')->where(['id' => $excel_id])->find();
        $new = [];
        $skudata = [];
        if (!empty($excel_data)) {
            foreach ($sku_data as $value) {
                if ($this->excel_transfer($brand, $value, $excel_data['attachfile']) == 'error') {
                    return error('当前模板没有对应尺码' . $value);
                };
                $new[] = $this->excel_transfer($brand, $value, $excel_data['attachfile']);
            }
        } else {
            foreach ($sku_data as $value) {
                $new[] = $this->excel_transfer($brand, $value, '', 2);
            }
        }
        $new_array = array();
        if (!empty($new)) {
            foreach ($new as $k => $v) {
                $skudata[$k]['name'] = $sku_name[$k] ? $sku_name[$k] : '';
                if (strstr($v, '+')) {
                    $skudata[$k]['sku'] = $v;
                    $new_array[] = $v;
                } else {
                    if ($quantity > 1) {
                        $skudata[$k]['sku'] = $v . '-' . $quantity;
                        $new_array[] = $v . '-' . $quantity;
                    } else {
                        $skudata[$k]['sku'] = $v;
                        $new_array[] = $v;
                    }
                }
                $skudata[$k]['option1'] = $option1[$k] ? $option1[$k] : '';
                $skudata[$k]['option2'] = $option2[$k] ? $option2[$k] : '';
                $skudata[$k]['option3'] = $option3[$k] ? $option3[$k] : '';
            }
        }
        $news['skudata'] = $skudata;
        $news['new'] = $new_array;
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $news,
        ];
        return json($data);
    }
    //excel 数据转换
    public function excel_transfer($brand = '', $value = 'Blue-38A', $attachfile = 'http://api.fan-zhoubuy.com/storage/system/20230414/5082ab88b750b00432c7fa96c2b3c76b.xls', $type = 1)
    {
        //切割颜色取出对应的值
        $explode_arr = explode('-', $value);
        if ($type == 2) {
            return strtolower($brand) . '-' . $explode_arr[0] . '-' . $explode_arr[1];
        } else {
            $excel_data = excel_data(excel_url($attachfile));
            if (!isset($excel_data[$explode_arr[1]])) {
                return 'error';
            }
            return strtolower($brand) . '-' . $explode_arr[0] . '-' . $excel_data[$explode_arr[1]];
        }
    }


    public function sku_table_deal()
    {
        $post = $this->request->post();
        $sku_table = table('sku_table')->where(['product_id' => $post['product_id']])->find();
        if ($sku_table) {
            table('sku_table')->where(['product_id' => $sku_table['product_id']])->update($post);
            table('product')->where(['id' => $sku_table['product_id']])->update(['table_status' => DicProduct::$table_status_1]);
            return success('更新成功');
        } else {
            table('sku_table')->insert($post);
            table('product')->where(['id' => $post['product_id']])->update(['table_status' => DicProduct::$table_status_1]);
            return success('新增成功');
        }
    }

    /**
     * SKU排行
     * @param array params
     */
    public function sku_ranking()
    {
        $post = $this->request->post();
        $sku_name = $post['start_time'] ? $post['start_time'] : 'bra01';
        $start_time = $post['start_time'] ? strtotime($post['start_time']) : mktime(0, 0, 0, date('m'), 1, date('Y'));
        $end_time =  time();
        $sql = "SELECT 
        c.sku,
        sum(b.quantity) as count,
        b.title,
        e.handle_url,
        b.product_id,
        c.variants_id as SKUid
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
        where a.financial_status = 'paid'
        AND a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        AND c.id > 1
        AND b.sku like '%{$sku_name}%'
        GROUP BY SKUid
        ORDER BY count DESC
    ";
        $join_datas = Db::query($sql);

        if (!$join_datas) {
            return [];
        }

        // halt($this->model->getlastsql());
        // halt(getsku());
        $colors = ['beige', 'black', 'blue', 'pink', 'skin', 'grey'];
        $sizes = ['m', 'l', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl', '7xl', '36', '38', '40', '42', '44', '46'];
        $merge_sku[$sku_name] = 0;
        foreach ($colors as  $color) {
            $merge_sku[$sku_name . '_' . $color] = 0;
            foreach ($sizes as $size) {
                $merge_sku[$sku_name . '_' . $color . '_' . $size] = 0;
            }
        }
        //bra01-black+blue-xl-2
        foreach ($join_datas as $join_data) {
            //数量
            $multiple = 1;
            $sku_title_arr =  explode('-', strtolower($join_data['sku']));
            file_put_contents('testsku.txt', $join_data['sku']);
            if (isset($sku_title_arr[0])) {
                if (isset($sku_title_arr[1])) {
                    if (isset($sku_title_arr[3])) {
                        $multiple = $sku_title_arr[3];
                    }
                    $sku_title_arr1 =  explode('+', $sku_title_arr[1]);
                    foreach ($sku_title_arr1 as $vl) {
                        $merge_sku[$sku_title_arr[0]] = $merge_sku[$sku_title_arr[0]] + ((int)$join_data['count']) * $multiple;
                        $merge_sku[$sku_title_arr[0] . '_' . $vl] = $merge_sku[$sku_title_arr[0] . '_' . $vl] + ((int)$join_data['count']) * $multiple;
                        if (isset($sku_title_arr[2])) {
                            $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]] = $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]]  + ((int)$join_data['count']) * $multiple;
                        }
                    }
                }
            }
        }
        foreach ($merge_sku as $k => $v) {
            if ($v == 0) {
                unset($merge_sku[$k]);
            }
        }
        $merge_sku_new = array();
        foreach ($merge_sku as $k => $v) {
            $merge_sku_new[] =
                ['sku' => $k, 'count' => $v];
        }
        // halt($merge_sku_new);
        $header = [['sku', 'sku'], ['count', 'count']];
        $fileName = $sku_name;
        return Excel::exportData($merge_sku_new, $header, $fileName, 'xlsx');
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => count($merge_sku_new),
            'data' => $merge_sku_new,
        ];
        return json($data);
    }


    //通过excel_id找excel对应数据
    public function get_excel_data()
    {
        $excel_id = input('excel_id') ? input('excel_id') : 1;
        $excel = table('demo_excel')->field('attachfile')->where(['id' => $excel_id])->find();
        $excel_data = excel_data(excel_url($excel['attachfile']));
        foreach ($excel_data as $key => $value) {
            $arr[] = ['cup' => $key, 'title' => $value];
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $arr,
        ];
        return json($data);
    }

    //首页判断运营权限
    public function judgment_authority()
    {
        $token = $this->request->header('token');
        $admin = Token::admin($token);
        if (!empty($admin)) {
            $group_admin = table('system_group_admin')
                // ->where('group_id', 5)
                ->where('admin_id', $admin['id'])
                ->find();
            if (!empty($group_admin)) {
                if ($group_admin['group_id'] == 5) {
                    return 5;
                }
                if ($group_admin['group_id'] == 1) {
                    return 1;
                }
            }
        }
        return 2;
    }
    //首页统计运营数据
    public function dashboard_new()
    {
        $post = $this->request->post();
        if (empty($post)) {
            $post['day_changes'] = 0;
            $post['start_time'] = time() - 15 * 3600;
            $post['end_time'] = time() + 9 * 3600;
        }

        //时区开始
        $start_time = $post['start_time'];
        $end_time = $post['end_time'];
        $start_time2 = $post['start_time'];
        $end_time2 = $post['end_time'];
        // $start_time2 = $post['start_time'] + 9 * 3600;
        // $end_time2 = $post['end_time'] + 9 * 3600;
        //时区1
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        //时区2
        $start_time2 = strtotime(date('Y-m-d 00:00:00', $start_time2));
        if ($post['day_changes'] == 3) {
            $start_time2 = strtotime(date('Y-m-1 00:00:00', $start_time2));
        }
        if ($post['day_changes'] == 101) {
            $end_time2 = strtotime(date('Y-m-d 23:59:59', $end_time2));
        } else {
            $end_time2 = strtotime(date('Y-m-d 00:00:00', $end_time2));
        }
        //时区结束

        $redis = new Redis();
        $dashboards = $redis->get('dashboard-new-' . $start_time . '-' . $end_time . '-' . $post['day_changes']);
        if (!empty($dashboards)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $dashboards,
            ];
            return json($data);
        }

        $exchange = $redis->get('exchangerate');
        if (empty($exchange)) {
            $exchange = table('exchange')
                ->where('currency', 'USD')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate', $exchange, 60 * 60 * 24);
        }
        $exchange_eur = $redis->get('exchangerate_eur');
        if (empty($exchange_eur)) {
            $exchange_eur = table('exchange')
                ->where('currency', 'EUR')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_eur', $exchange_eur, 60 * 60 * 24);
        }
        $exchange_mxn = $redis->get('exchangerate_mxn');
        if(empty($exchange_mxn)){
            $exchange_mxn = table('exchange')
                ->where('currency','MXN')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_mxn', $exchange_mxn, 60 * 60 * 24 );
        }
        //站点
        // $integration = $redis->get('integration');
        // if(empty($integration)){
        //     $site_arr = table('site')
        //         ->field('id,site_name,international_sites')
        //         ->where('status','normal')
        //         ->select()->toarray();
        //     $site_total_new = array();
        //     $site_total_new2 = array();
        //     $integration = array();
        //     foreach ($site_arr as $k=>$v) {
        //         $site_total_new[$v['id']] = $v['site_name'];
        //         $site_total_new2[$v['id']] = $v['international_sites'];
        //     }
        //     $integration['site_total_new'] = $site_total_new;
        //     $integration['site_total_new2'] = $site_total_new2;
        //     $redis->set('integration', $integration, 60 * 60 * 24 );
        // }else{
        //     $site_total_new = $integration['site_total_new'];
        //     $site_total_new2 = $integration['site_total_new2'];
        // }
        //站点

        //arr
        $arr = array();
        $arr['paid'] = 0;
        $arr['sales'] = 0;
        $arr['dispute'] = 0;
        $arr['refund_money'] = 0;
        $arr['sales_usd'] = 0;
        $arr['sales_eur'] = 0;
        $arr['estimated_cost'] = 0;
        $arr['gross_profit'] = 0;
        $arr['logistics'] = 0;
        $arr['roi'] = 0;
        $arr['purchase'] = 0;
        $arr['adv_cost'] = 0;
        $arr['platform_discount'] = 0;

        //
        //店铺业绩
        $where1 = array();
        $where1[]  = ['a.created_at', '>=', $start_time];
        $where1[]  = ['a.created_at', '<=', $end_time];

        $where2 = array();
        $where2[]  = ['a.created_at', '>=', $start_time2];
        $where2[]  = ['a.created_at', '<=', $end_time2];

        $where_total_price[] = ['a.financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];
        $shopify_sales_arr = array();

        $shopify_sales1 = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->field('a.site_id,sum(total_price) as total,sum(countnum) as count,a.currency,sum(freight) as freight,sum(material) as material,b.international_sites,b.site_name')
            ->where($where1)
            ->where($where_total_price)
            ->where('international_sites', '美国站')
            ->where(['a.status' => DicSite::$status_normal])
            ->where(['b.status' => DicSite::$status_normal])
            ->group('site_id')
            ->order('total desc')
            ->select()->toarray();
        if (!empty($shopify_sales1)) {
            foreach ($shopify_sales1 as $k => $v) {
                // unset($site_total_new[$v['site_id']]);
                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time];
                $wheregroup['a.site_id'] = $v['site_id'];
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if (!isset($site_log['nickname']) || empty($site_log['nickname'])) {
                    $site_log['nickname'] = '';
                }

                $zsales = (float)number_format($v['total'], 3, '.', '');
                $shopify_sales_remarks = '';
                if ($v['currency'] == 'EUR') {
                    $shopify_sales_remarks = '原销售额为€' . $zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                if ($v['currency'] == 'MXN') {
                    $shopify_sales_remarks = '原销售额为Mex$' . $zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_mxn['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                //广告
                $start_time_str = date('Y-m-d H:i:s', $start_time);
                $end_time_str =  date('Y-m-d H:i:s', $end_time);
                $adv_where = array();
                $adv_where[]  = ['create_time', '>=', $start_time_str];
                $adv_where[]  = ['create_time', '<', $end_time_str];
                $zadvcost_z = array();
                $advplat_arr = table('advplat')
                    ->where('site_id', $v['site_id'])
                    ->select()->toarray();
                $zadvcost_new = 0;
                $zadvcost_msg = array();
                if (!empty($advplat_arr)) {
                    foreach ($advplat_arr as $k0 => $v0) {
                        $zadvcost_z2 = table('advertising')
                            ->field('a.*,b.title')
                            ->alias('a')
                            ->join('qu_advplatform b','b.id = a.plat', 'left')
                            ->where($adv_where)
                            ->where('a.plat_account', $v0['id'])
                            ->where('a.status', 'normal')
                            ->select()->toarray();
                        if (!empty($zadvcost_z2)) {
                            foreach ($zadvcost_z2 as $k1 => $v1) {
                                if(isset($zadvcost_msg[$v1['title']])){
                                    $zadvcost_msg[$v1['title']] = $zadvcost_msg[$v1['title']] + (float)$v1['cost'];
                                }else{
                                    $zadvcost_msg[$v1['title']] = (float)$v1['cost'];
                                }
                                $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v1['cost'], 3, '.', '');
                            }
                        }
                    }
                }
                $zadvcost_msg2 = '';
                if(!empty($zadvcost_msg)){
                    foreach ($zadvcost_msg as $kadmsg=>$vadmsg) {
                        if(!empty($zadvcost_msg2)){
                            $zadvcost_msg2 = $zadvcost_msg2 .','.$kadmsg.':'.$vadmsg;
                        }else{
                            $zadvcost_msg2 = $kadmsg.':'.$vadmsg;
                        }
                    }
                }
                //广告结束
                //时间段退款
                $where_refund = array();
                $where_refund[]  = ['processed_at', '>=', $start_time];
                $where_refund[]  = ['processed_at', '<=', $end_time];
                $where_refund[]  = ['refund_status', '<=', 'success'];
                $sales_refund = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $v['site_id']])
                    ->sum('amount');
                $sales_refund = (float)number_format($sales_refund, 3, '.', '');

                $v['freight'] = (float)number_format((float)$v['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $v['material'] = (float)number_format((float)$v['material'] / (float)$exchange['proportion'], 3, '.', '');
                $gross_profit = (float)number_format((float)$zsales * 0.94 - (float)$v['freight'] - (float)$v['material'] - $zadvcost_new, 3, '.', '');
                if ($zsales > 0.02 && $zadvcost_new > 0.02) {
                    $roi = (float)number_format((float)$zsales / (float)$zadvcost_new, 3, '.', '');
                } else {
                    $roi = 0;
                }
                $arr['sales'] = (float)number_format($zsales + $arr['sales'], 3, '.', '');
                $arr['logistics'] = (float)number_format($v['freight'] + $arr['logistics'], 3, '.', '');
                $arr['purchase'] = (float)number_format($v['material'] + $arr['purchase'], 3, '.', '');
                $arr['adv_cost'] = (float)number_format($zadvcost_new + $arr['adv_cost'], 3, '.', '');
                $arr['sales_usd'] = (float)number_format($zsales + $arr['sales_usd'], 3, '.', '');
                $arr['paid'] = (float)number_format($v['count'] + $arr['paid'], 3, '.', '');
                $arr['refund_money'] = (float)number_format($sales_refund + $arr['refund_money'], 3, '.', '');
                $shopify_sales_arr[] = [
                    'id' => $v['site_id'],
                    'name' => $v['site_name'],
                    'gross_profit' => $gross_profit,
                    'count' => (int)$v['count'],
                    'sales' => $zsales,
                    'refund' => $sales_refund,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'freight' => $v['freight'],
                    'material' => $v['material'],
                    'roi' => $roi,
                    'remarks' => $shopify_sales_remarks,
                    'zadvcost_msg2' => $zadvcost_msg2,
                ];
            }
        }
        $shopify_sales2 = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->field('a.site_id,sum(total_price) as total,sum(countnum) as count,a.currency,sum(freight) as freight,sum(material) as material,b.international_sites,b.site_name')
            ->where($where2)
            ->where($where_total_price)
            ->where('international_sites', '欧洲站')
            ->group('site_id')
            ->order('total desc')
            ->select()->toarray();
        if (!empty($shopify_sales2)) {
            foreach ($shopify_sales2 as $k => $v) {
                // unset($site_total_new[$v['site_id']]);
                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time2];
                $wheregroup['a.site_id'] = $v['site_id'];
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if (!isset($site_log['nickname']) || empty($site_log['nickname'])) {
                    $site_log['nickname'] = '';
                }

                $zsales = (float)number_format($v['total'], 3, '.', '');
                $shopify_sales_remarks = '';
                $old_sales = 0;
                if ($v['currency'] == 'EUR') {
                    $old_sales = $zsales;
                    $shopify_sales_remarks = '原销售额为€' . $zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                if ($v['currency'] == 'MXN') {
                    $old_sales = $zsales;
                    $shopify_sales_remarks = '原销售额为Mex$' . $zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_mxn['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                //广告
                $start_time_str2 = date('Y-m-d H:i:s', $start_time2);
                $end_time_str2 =  date('Y-m-d H:i:s', $end_time2);
                $adv_where = array();
                $adv_where[]  = ['create_time', '>=', $start_time_str2];
                $adv_where[]  = ['create_time', '<', $end_time_str2];
                $zadvcost_z2 = array();
                $advplat_arr = table('advplat')
                    ->where('site_id', $v['site_id'])
                    ->select()->toarray();
                $zadvcost_new = 0;
                $zadvcost_msg = array();
                if (!empty($advplat_arr)) {
                    foreach ($advplat_arr as $k0 => $v0) {
                        $zadvcost_z2 = table('advertising')
                            ->field('a.*,b.title')
                            ->alias('a')
                            ->join('qu_advplatform b','b.id = a.plat', 'left')
                            ->where($adv_where)
                            ->where('a.plat_account', $v0['id'])
                            ->where('a.status', 'normal')
                            ->select()->toarray();
                        if (!empty($zadvcost_z2)) {
                            foreach ($zadvcost_z2 as $k1 => $v1) {
                                if(isset($zadvcost_msg[$v1['title']])){
                                    $zadvcost_msg[$v1['title']] = $zadvcost_msg[$v1['title']] + (float)$v1['cost'];
                                }else{
                                    $zadvcost_msg[$v1['title']] = (float)$v1['cost'];
                                }
                                $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v1['cost'], 3, '.', '');
                            }
                        }
                    }
                }
                $zadvcost_msg2 = '';
                if(!empty($zadvcost_msg)){
                    foreach ($zadvcost_msg as $kadmsg=>$vadmsg) {
                        if(!empty($zadvcost_msg2)){
                            $zadvcost_msg2 = $zadvcost_msg2 .','.$kadmsg.':'.$vadmsg;
                        }else{
                            $zadvcost_msg2 = $kadmsg.':'.$vadmsg;
                        }
                    }
                }
                //广告结束
                //时间段退款
                $where_refund = array();
                $where_refund[]  = ['processed_at', '>=', $start_time2];
                $where_refund[]  = ['processed_at', '<=', $end_time2];
                $where_refund[]  = ['refund_status', '<=', 'success'];
                $sales_refund = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $v['site_id']])
                    ->sum('amount');
                $sales_refund = (float)number_format($sales_refund, 3, '.', '');

                $v['freight'] = (float)number_format((float)$v['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $v['material'] = (float)number_format((float)$v['material'] / (float)$exchange['proportion'], 3, '.', '');
                $gross_profit = (float)number_format((float)$zsales * 0.94 - (float)$v['freight'] - (float)$v['material'] - $zadvcost_new, 3, '.', '');
                if ($zsales > 0.02 && $zadvcost_new > 0.02) {
                    $roi = (float)number_format((float)$zsales / (float)$zadvcost_new, 3, '.', '');
                } else {
                    $roi = 0;
                }

                $arr['sales'] = (float)number_format($zsales + $arr['sales'], 3, '.', '');
                $arr['logistics'] = (float)number_format($v['freight'] + $arr['logistics'], 3, '.', '');
                $arr['purchase'] = (float)number_format($v['material'] + $arr['purchase'], 3, '.', '');
                $arr['adv_cost'] = (float)number_format($zadvcost_new + $arr['adv_cost'], 3, '.', '');
                $arr['sales_eur'] = (float)number_format($old_sales + $arr['sales_eur'], 3, '.', '');
                $arr['paid'] = (float)number_format($v['count'] + $arr['paid'], 3, '.', '');
                $arr['refund_money'] = (float)number_format($sales_refund + $arr['refund_money'], 3, '.', '');
                $shopify_sales_arr[] = [
                    'id' => $v['site_id'],
                    'name' => $v['site_name'],
                    'gross_profit' => $gross_profit,
                    'count' => (int)$v['count'],
                    'sales' => $zsales,
                    'refund' => $sales_refund,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'roi' => $roi,
                    'remarks' => $shopify_sales_remarks,
                    'zadvcost_msg2' => $zadvcost_msg2,
                ];
            }
        }
        //店铺业绩结束

        // if(!empty($site_total_new)){
        //     foreach ($site_total_new as $kst => $vst) {
        //         if(isset($site_total_new2[$kst]) && !empty($site_total_new2[$kst])){
        //                 //时间段退款
        //         }
        //     }
        // }
        $arr['platform_discount'] = (float)number_format($arr['sales'] * 0.06, 3, '.', '');
        $arr['gross_profit_handle1'] = '销售额-物流-采购-广告-手续费(6%)';
        $arr['gross_profit_handle2'] = $arr['sales'] . '-' . $arr['logistics'] . '-' . $arr['purchase'] . '-' . $arr['adv_cost'] . '-' . $arr['platform_discount'];
        $arr['gross_profit'] = (float)number_format($arr['sales'] * 0.94 - (float)$arr['logistics'] - (float)$arr['purchase'] - (float)$arr['adv_cost'], 2, '.', '');
        $newarr = array();
        $newarr['arr'][] = $arr;
        $newarr['shopify_sales'] = $shopify_sales_arr;
        $redis->set('dashboard-new-' . $start_time . '-' . $end_time . '-' . $post['day_changes'], $newarr, 60 * 3);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $newarr,
        ];
        return json($data);
    }

    //首页统计运营数据
    public function dashboard_new_edit()
    {
        $id = input('id');
        $post_start_time = input('post_start_time');
        $post_end_time = input('post_end_time');

        if (empty($id) || empty($post_start_time) || empty($post_end_time)) {
            return error('参数错误,请稍后再试');
        }

        $row['id'] = $id;
        $row['post_start_time'] = date('Y-m-d', $post_start_time);
        $row['post_end_time'] = date('Y-m-d', $post_end_time);
        //运营业绩详情
        $site = table('site')->where(['id' => $id])->find();
        $row['site_name'] = $site['site_name'];

        if ($this->request->isPost()) {
            $post = $this->request->post();
            return success('保存成功！');
        }


        return success('ok', $row);
    }
    //个人业绩
    public function dashboard_personal()
    {
        $post = $this->request->post();
        if (isset($post['admin_id']) && !empty($post['admin_id'])) {
            $adv_where[] = ['admin_id', 'in', $post['admin_id']];
            $where_day[] = ['admin_id', 'in', $post['admin_id']];

            $post['admin_type'] = implode(',', $post['admin_id']);
        } else {
            $post['admin_type'] = 0;
        }
        $start_time = !empty($post['start_time']) ? $post['start_time'] : strtotime(date('Y-m-d 00:00:00', time() - 15 * 3600));
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        $start_time_str = date('Y-m-d H:i:s', $start_time);
        $end_time = !empty($post['end_time']) ? $post['end_time'] : strtotime(date('Y-m-d 00:00:00', time() + 9 * 3600));
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        $end_time_str =  date('Y-m-d H:i:s', $end_time);
        $redis = new Redis();
        $dashboards = $redis->get('dashboard-personal-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['admin_type']);
        if (!empty($dashboards)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $dashboards,
            ];
            return json($data);
        }

        $exchange = $redis->get('exchangerate');
        if (empty($exchange)) {
            $exchange = table('exchange')
                ->where('currency', 'USD')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate', $exchange, 60 * 60 * 24);
        }
        $exchange_eur = $redis->get('exchangerate_eur');
        if (empty($exchange_eur)) {
            $exchange_eur = table('exchange')
                ->where('currency', 'EUR')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_eur', $exchange_eur, 60 * 60 * 24);
        }
        $exchange_mxn = $redis->get('exchangerate_mxn');
        if(empty($exchange_mxn)){
            $exchange_mxn = table('exchange')
                ->where('currency','MXN')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_mxn', $exchange_mxn, 60 * 60 * 24 );
        }

        $adv_where[]  = ['create_time', '>=', $start_time_str];
        $adv_where[]  = ['create_time', '<', $end_time_str];

        $arr = array();
        //运营业绩
        $where_day[]  = ['time_stamp', '>=', $start_time];
        $where_day[]  = ['time_stamp', '<', $end_time];
        $shopify_sales_day = table('shopify_personreport_day')
            ->field('admin_id,sum(total_price) as total,sum(count) as counts,label,site_id,sum(freight) as freight,sum(material) as material,label_type,currency')
            ->where($where_day)
            ->group('admin_id,site_id')
            ->order('total desc')
            ->select()
            ->toarray();

        $newarr = array();
        $newarr['paid'] = 0;
        $newarr['sales_usd'] = 0;
        $newarr['sales_eur'] = 0;
        $newarr['sales_mxn'] = 0;
        $newarr['sales'] = 0;
        $newarr['gross_profit'] = 0;
        $newarr['adv_cost'] = 0;
        $newarr['logistics'] = 0;
        $newarr['purchase'] = 0;
        $newarr['platform_discount'] = 0;

        $group_admin = table('system_group_admin')
            ->field('admin_id')
            ->where('group_id', 5)
            ->select()->toarray();
        foreach ($group_admin as $kg => $vg) {
            $group_admin_new[$vg['admin_id']] = $vg['admin_id'];
        }
        if (!empty($shopify_sales_day)) {
            //店铺销售额
            $where1 = array();
            $where1[]  = ['created_at', '>=', $start_time];
            $where1[]  = ['created_at', '<=', $end_time];
            $where_total_price[] = ['financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];
            $site_array = table('order')
                ->field('site_id')
                ->where($where1)
                ->where($where_total_price)
                ->group('site_id')
                ->select()->toarray();
            foreach ($site_array as $ks => $vs) {
                $sites = table('site')->where(['id' => $vs['site_id']])->find();
                $site_array_new[$vs['site_id']] = $sites['site_name'];
            }
            if (!empty($site_array_new)) {
                $site_array_new2 = $site_array_new;
            }
            foreach ($shopify_sales_day as $key => $value) {
                if (isset($group_admin_new[$value['admin_id']])) {
                    unset($group_admin_new[$value['admin_id']]);
                }
                switch ($value['label_type']) {
                    case '1':
                        $value['label_type'] = '主运营';
                        break;
                    case '2':
                        $value['label_type'] = '副运营';
                        break;
                    default:
                        $value['label_type'] = '未知';
                }
                switch ($value['currency']) {
                    case 'USD':
                        $value['currency'] = '$';
                        $newarr['sales_usd'] = (float)number_format((float)$value['total'] + $newarr['sales_usd'], 3, '.', '');
                        break;
                    case 'EUR':
                        $value['currency'] = '€';
                        $newarr['sales_eur'] = (float)number_format((float)$value['total'] + $newarr['sales_eur'], 3, '.', '');
                        $value['total'] = (float)number_format((float)$value['total'] * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                        break;
                    case 'MXN':
                        $value['currency'] = 'Mex$';
                        $newarr['sales_mxn'] = (float)number_format((float)$value['total'] + $newarr['sales_mxn'], 3, '.', '');
                        $value['total'] = (float)number_format((float)$value['total'] * (float)$exchange_mxn['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                        break;
                    default:
                        $value['currency'] = '未知';
                }
                if (isset($site_array_new2[$value['site_id']])) {
                    $value['site_name'] = $site_array_new2[$value['site_id']];
                    unset($site_array_new[$value['site_id']]);
                }
                $new_shopify_sales_day[$value['admin_id']][] = $value;
            }
            if (!empty($new_shopify_sales_day)) {
                foreach ($new_shopify_sales_day as $k2 => $v2) {
                    $sales_days2 = array();
                    $system_admin = table('system_admin')->where(['id' => $k2])->find();
                    if (!empty($system_admin)) {
                        $sales_days['admin_name'] = $system_admin['nickname'];
                        $sales_days['team_id'] = $system_admin['team_id'];
                    } else {
                        $sales_days['admin_name'] = '未知';
                        $sales_days['team_id'] = 0;
                    }
                    //备注
                    $sales_days['total'] = 0;
                    $sales_days['counts'] = 0;
                    $sales_days['freight'] = 0;
                    $sales_days['material'] = 0;
                    $sales_days['remarks'] = array();
                    foreach ($v2 as $k3 => $v3) {
                        $sales_days['total'] = (float)number_format((float)$sales_days['total'] + (float)$v3['total'], 3, '.', '');
                        $sales_days['counts'] = (int)number_format((int)$sales_days['counts'] + (int)$v3['counts'], 3, '.', '');
                        $sales_days['freight'] = (float)number_format((float)$sales_days['freight'] + (float)$v3['freight'], 3, '.', '');
                        $sales_days['material'] = (float)number_format((float)$sales_days['material'] + (float)$v3['material'], 3, '.', '');
                        $sales_days['remarks'][] = $v3;
                    }
                    $where_admin['admin_id'] = $k2;
                    $zadvcost_z = table('advertising')
                        ->field('sum(cost) as cost')
                        ->where($adv_where)
                        ->where('status', 'normal')
                        ->where($where_admin)
                        ->find();
                    if (!empty($zadvcost_z['cost'])) {
                        $sales_days['advcost'] = number_format($zadvcost_z['cost'], 3, '.', '');
                    } else {
                        $sales_days['advcost'] = 0;
                    }
                    $sales_days['roi'] = 0;
                    if ($sales_days['advcost'] > 0.001 && $sales_days['total'] > 0.001) {
                        $sales_days['roi'] = number_format((float)$sales_days['total'] / (float)$sales_days['advcost'], 3, '.', '');
                    } //转化率ROI
                    $sales_days['freight'] = (float)number_format((float)$sales_days['freight'] / (float)$exchange['proportion'], 3, '.', '');
                    $sales_days['material'] = (float)number_format((float)$sales_days['material'] / (float)$exchange['proportion'], 3, '.', '');
                    //毛利计算新增规则
                    $sales_days['profit'] = (float)number_format((float)$sales_days['total'] * 0.94 - (float)$sales_days['freight'] - (float)$sales_days['material'] - (float)$sales_days['advcost'], 3, '.', '');
                    // 分组
                    if ($system_admin['team_id'] == 1) {
                        $arr['shopify_sales_day_wh'][] = $sales_days;
                    } elseif ($system_admin['team_id'] == 2) {
                        $arr['shopify_sales_day_nc'][] = $sales_days;
                    } elseif ($system_admin['team_id'] == 3) {
                        $arr['shopify_sales_day_yc'][] = $sales_days;
                    }
                    $arr['shopify_sales_day'][] = $sales_days;
                    //统计
                    $newarr['paid'] = (int)number_format($newarr['paid'] + $sales_days['counts'], 3, '.', '');
                    $newarr['sales'] = (float)number_format($newarr['sales'] + $sales_days['total'], 2, '.', '');
                    $newarr['adv_cost'] = (float)number_format($newarr['adv_cost'] + $sales_days['advcost'], 3, '.', '');
                    $newarr['logistics'] = (float)number_format($newarr['logistics'] + $sales_days['freight'], 3, '.', '');
                    $newarr['purchase'] = (float)number_format($newarr['purchase'] + $sales_days['material'], 3, '.', '');
                }
            }
            //暂无运营
            if (!empty($site_array_new) && $post['admin_type'] == 0) {
                //店铺销售额
                $where1 = array();
                $where1[]  = ['created_at', '>=', $start_time];
                $where1[]  = ['created_at', '<=', $end_time];
                $where_total_price[] = ['financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];

                $sales_days2 = array();
                $sales_days2['total'] = 0;
                $sales_days2['counts'] = 0;
                $sales_days2['freight'] = 0;
                $sales_days2['material'] = 0;
                $sales_days2['remarks'] = array();
                foreach ($site_array_new as $ks => $vs) {
                    $shopify_sales2 = table('order')
                        ->field('site_id,sum(total_price) as total,sum(countnum) as counts,currency,sum(freight) as freight,sum(material) as material')
                        ->where($where1)
                        ->where($where_total_price)
                        ->where('site_id', $ks)
                        ->find();
                    switch ($shopify_sales2['currency']) {
                        case 'USD':
                            $sales_days2['total'] = (float)number_format((float)$sales_days2['total'] + (float)$shopify_sales2['total'], 3, '.', '');
                            $newarr['sales_usd'] = (float)number_format((float)$shopify_sales2['total'] + $newarr['sales_usd'], 3, '.', '');
                            break;
                        case 'EUR':
                            $shopify_sales2['total'] = (float)number_format((float)$shopify_sales2['total'] * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                            $sales_days2['total'] = (float)number_format((float)$sales_days2['total'] + (float)$shopify_sales2['total'], 3, '.', '');
                            $newarr['sales_eur'] = (float)number_format((float)$shopify_sales2['total'] + $newarr['sales_eur'], 3, '.', '');
                            break;
                        case 'MXN':
                            $shopify_sales2['total'] = (float)number_format((float)$shopify_sales2['total'] * (float)$exchange_mxn['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                            $sales_days2['total'] = (float)number_format((float)$sales_days2['total'] + (float)$shopify_sales2['total'], 3, '.', '');
                            $newarr['sales_mxn'] = (float)number_format((float)$shopify_sales2['total'] + $newarr['sales_mxn'], 3, '.', '');
                            break;
                        default:
                            $sales_days2['total'] = (float)number_format((float)$sales_days2['total'] + (float)$shopify_sales2['total'], 3, '.', '');
                    }
                    $sales_days2['counts'] = (int)number_format((int)$sales_days2['counts'] + (int)$shopify_sales2['counts'], 3, '.', '');
                    $shopify_sales2['freight'] = (float)number_format((float)$shopify_sales2['freight'] / (float)$exchange['proportion'], 3, '.', '');
                    $shopify_sales2['material'] = (float)number_format((float)$shopify_sales2['material'] / (float)$exchange['proportion'], 3, '.', '');
                    $sales_days2['freight'] = (float)number_format((float)$sales_days2['freight'] + (float)$shopify_sales2['freight'], 3, '.', '');
                    $sales_days2['material'] = (float)number_format((float)$sales_days2['material'] + (float)$shopify_sales2['material'], 3, '.', '');
                    $remarks2['site_name'] = $vs;
                    $remarks2['label_type'] = '';
                    $remarks2['total'] = (float)$shopify_sales2['total'];
                    $sales_days2['remarks'][] = $remarks2;
                }
                $sales_days2['admin_name'] = '暂无运营管理';
                $sales_days2['profit'] = '';
                $sales_days2['advcost'] = '';
                $sales_days2['roi'] = '';
                $arr['shopify_sales_day'][] = $sales_days2;
                $newarr['sales'] = (float)number_format($newarr['sales'] + $sales_days2['total'], 2, '.', '');
                $newarr['paid'] = (int)number_format($newarr['paid'] + $sales_days2['counts'], 3, '.', '');
                $newarr['logistics'] = (float)number_format($newarr['logistics'] + $sales_days2['freight'], 3, '.', '');
                $newarr['purchase'] = (float)number_format($newarr['purchase'] + $sales_days2['material'], 3, '.', '');
            }
        }
        if ($post['admin_type'] == 0) {
            //存在出广告费没业绩的运营
            foreach ($group_admin_new as $kga => $vga) {
                $where_admin['admin_id'] = $kga;
                $zadvcost_ga = table('advertising')
                    ->field('sum(cost) as cost,admin_id')
                    ->where($adv_where)
                    ->where('status', 'normal')
                    ->where($where_admin)
                    ->find();
                if (!empty($zadvcost_ga['cost'])) {
                    $sales_days = array();
                    $system_admin = table('system_admin')->where(['id' => $kga])->find();
                    if (!empty($system_admin)) {
                        $sales_days['admin_name'] = $system_admin['nickname'];
                    } else {
                        $sales_days['admin_name'] = '未知';
                    }
                    $sales_days['total'] = 0;
                    $sales_days['counts'] = 0;
                    $sales_days['freight'] = 0;
                    $sales_days['material'] = 0;
                    $sales_days['advcost'] = $zadvcost_ga['cost'];
                    $remarks3['site_name'] = '没出单但有广告费';
                    $remarks3['label_type'] = '';
                    $remarks3['total'] = 0;
                    $sales_days['remarks'][] = $remarks3;
                    $newarr['adv_cost'] = (float)number_format((float)$newarr['adv_cost'] + (float)$sales_days['advcost'], 3, '.', '');
                    $arr['shopify_sales_day'][] = $sales_days;
                }
            }
        }

        $newarr['platform_discount'] = (float)number_format((float)$newarr['sales'] * 0.06, 3, '.', '');
        $newarr['gross_profit'] = (float)number_format($newarr['sales'] - (float)$newarr['logistics'] - (float)$newarr['purchase'] - (float)$newarr['adv_cost'] - (float)$newarr['platform_discount'], 2, '.', '');
        $arr['newarr'][] = $newarr;

        $redis->set('dashboard-personal-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['admin_type'], $arr, 60 * 5);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $arr,
        ];
        return json($data);
    }

    /**
     * 方法详情
     * @param array params
     */
    public function dashboard_site()
    {
        $redis = new Redis();
        $site_arr = $redis->get('site_arr');
        if (!empty($site_arr)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $site_arr,
            ];
            return json($data);
        }
        $site_arr =  table('site')
            ->field("id,site_name,site_number")
            ->where(['status' => 'normal'])
            ->order('popular desc')
            ->select()->toarray();
        $redis->set('site_arr', $site_arr, 60 * 30);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $site_arr,
        ];
        return json($data);
    }

    /**
     * 方法详情
     * @param array params
     */
    public function dashboard_admin()
    {
        $redis = new Redis();
        $system_admin = $redis->get('system_admin');
        if (!empty($system_admin)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $system_admin,
            ];
            return json($data);
        }
        $system_admin =  table('system_admin')
            ->field("a.id,a.nickname,a.team_id")
            ->field("a.*")
            ->alias('a')
            ->join('qu_system_group_admin b', 'b.admin_id = a.id', 'left')
            ->where(['a.status' => 1])
            ->where(['b.group_id' => 5])
            ->order('a.popular desc')
            ->select()->toarray();
        foreach ($system_admin as $k => $v) {
            switch ($v['team_id']) {
                case '1':
                    $system_admin[$k]['team_name'] = '武汉';
                    break;
                case '2':
                    $system_admin[$k]['team_name'] = '南昌';
                    break;
                case '3':
                    $system_admin[$k]['team_name'] = '银川';
                    break;
                default:
                    $system_admin[$k]['team_name'] = '未知';
            }
        }

        $redis->set('system_admin', $system_admin, 60 * 30);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $system_admin,
        ];
        return json($data);
    }


    //首页统计运营数据
    public function dashboard_shop()
    {
        $post = $this->request->post();

        if (isset($post['site_id']) && !empty($post['site_id'])) {
            $where[] = ['site_id', 'in', $post['site_id']];
            $where2[] = ['a.site_id', 'in', $post['site_id']];
            $where_refund[] = ['site_id', 'in', $post['site_id']];
            $where_dispute[] = ['site_id', 'in', $post['site_id']];

            $post['site_type'] = implode(',', $post['site_id']);
        } else {
            $post['site_type'] = 0;
        }
        $start_time = !empty($post['start_time']) ? $post['start_time'] : strtotime(date('Y-m-d 00:00:00', time() - 15 * 3600));
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        $start_time_str = date('Y-m-d H:i:s', $start_time);
        $end_time = !empty($post['end_time']) ? $post['end_time'] : strtotime(date('Y-m-d 00:00:00', time() + 9 * 3600));
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        $today = strtotime(date('Y-m-d 23:59:59', time()));
        if ($end_time >= $today) {
            return error('未生成今日报表');
        }
        $end_time_str =  date('Y-m-d H:i:s', $end_time);
        $redis = new Redis();
        $dashboards = $redis->get('dashboard-shop-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['site_type']);
        if (!empty($dashboards)) {
            $data = [
                'code' => 1,
                'msg' => '缓存数据',
                'data' => $dashboards,
            ];
            return json($data);
        }
        $exchange = $redis->get('exchangerate');
        if (empty($exchange)) {
            $exchange = table('exchange')
                ->where('currency', 'USD')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate', $exchange, 60 * 60 * 24);
        }
        $exchange_eur = $redis->get('exchangerate_eur');
        if (empty($exchange_eur)) {
            $exchange_eur = table('exchange')
                ->where('currency', 'EUR')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_eur', $exchange_eur, 60 * 60 * 24);
        }
        $exchange_mxn = $redis->get('exchangerate_mxn');
        if(empty($exchange_mxn)){
            $exchange_mxn = table('exchange')
                ->where('currency','MXN')
                ->order('date desc')
                ->find();
            $redis->set('exchangerate_mxn', $exchange_mxn, 60 * 60 * 24 );
        }
        $where[]  = ['created_at', '>=', $start_time];
        $where[]  = ['created_at', '<=', $end_time];
        $where_total_price[] = ['financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];
        //已支付 + 部分退款 金额
        $where2[]  = ['a.created_at', '>=', $start_time];
        $where2[]  = ['a.created_at', '<=', $end_time];
        $where_total_price2[] = ['a.financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];
        $statistics = table('order')
            ->field('sum(a.total_price) as total_price,sum(a.freight) as freight,sum(a.material) as material')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where($where_total_price2)
            ->where(['a.status' => DicSite::$status_normal])
            ->find(); //总销售额

        $statistics1 = table('order')
            ->field('sum(a.total_price) as total_price,currency')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where($where_total_price2)
            ->where(['a.status' => DicSite::$status_normal])
            ->group('currency')
            ->select()->toarray(); //总销售额
        $arr['sales'] = 0;
        $arr['sales_eur'] = 0;
        $arr['sales_usd'] = 0;
        $arr['sales_mxn'] = 0;
        if (!empty($statistics1)) {
            foreach ($statistics1 as $ks => $vs) {
                if ($vs['currency'] == 'EUR') {
                    $arr['sales_eur'] = (float)number_format((float)$vs['total_price'], 3, '.', '');
                    $sales_eur = (float)number_format((float)$arr['sales_eur'] * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                    $arr['sales'] = $arr['sales'] + $sales_eur;
                }
                if ($vs['currency'] == 'USD') {
                    $arr['sales_usd'] = (float)number_format((float)$vs['total_price'], 3, '.', '');
                    $arr['sales'] = $arr['sales'] + $arr['sales_usd'];
                }
                if ($vs['currency'] == 'MXN') {
                    $arr['sales_mxn'] = (float)number_format((float)$vs['total_price'], 3, '.', '');
                    $sales_mxn = (float)number_format((float)$arr['sales_mxn'] * (float)$exchange_mxn['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                    $arr['sales'] = $arr['sales'] + $sales_mxn;
                }
            }
        }

        $arr['sales'] = (float)number_format((float)$arr['sales'], 2, '.', '');
        $arr['platform_discount'] = (float)number_format((float)$arr['sales'] * 0.06, 3, '.', '');
        $arr['logistics'] = (float)number_format((float)$statistics['freight'] / (float)$exchange['proportion'], 3, '.', '');
        $arr['purchase'] = (float)number_format((float)$statistics['material'] / (float)$exchange['proportion'], 3, '.', '');

        $arr['paid'] = table('order')
            ->alias('a')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where($where_total_price2)
            ->where(['a.status' => DicSite::$status_normal])
            ->count(); //支付订单
        $arr['authorized'] = 0;
        $arr['authorized_info'] = '';
        $authorized_info = table('order')
            ->alias('a')
            ->field('sum(countnum) as countnum,b.site_name')
            ->join('qu_site b', 'b.id = a.site_id', 'left')
            ->where($where2)
            ->where(['a.financial_status' => 'authorized'])
            ->group('b.id')
            ->select()->toarray();
        foreach ($authorized_info as $k => $v) {
            if (!empty($arr['authorized_info'])) {
                $arr['authorized_info'] = $arr['authorized_info'] . '
                    |
                    ' . $v['site_name'] . '店铺有' . $v['countnum'] . '单';
            } else {
                $arr['authorized_info'] = $v['site_name'] . '店铺有' . $v['countnum'] . '单';
            }
            $arr['authorized'] = $arr['authorized'] + $v['countnum'];
        }

        //退款
        $where_refund[]  = ['processed_at', '>=', $start_time];
        $where_refund[]  = ['processed_at', '<=', $end_time];
        $where_refund[]  = ['refund_status', '<=', 'success'];
        $arr['refund'] = table('order_refunds')->where($where_refund)->count(); //退款订单
        $arr['refund_money'] = number_format(table('order_refunds')->where($where_refund)->sum('amount'), 2, '.', ''); //退款金额

        //争议单
        $where_dispute[]  = ['createtime', '>=', $start_time];
        $where_dispute[]  = ['createtime', '<=', $end_time];
        $arr['dispute'] = table('order_dispute')->where($where_dispute)->count();
        //FB广告消耗金额图表

        $adv_where[]  = ['a.create_time', '>=', $start_time_str];
        $adv_where[]  = ['a.create_time', '<', $end_time_str];
        $arr['adv_cost'] = 0;

        $shopify_sales_arr = array();
        //店铺销售额
        $shopify_sales = table('order')->field('site_id,sum(total_price) as total,sum(countnum) as count,currency,sum(freight) as freight,sum(material) as material')->where($where)->where($where_total_price)->group('site_id')->order('total desc')->select()->toarray(); //总销售额
        $site_total = table('site')
            ->field('id,site_name')
            ->where('status', 'normal')
            ->select()->toarray();
        $site_total_new = array();
        foreach ($site_total as $k => $v) {
            $site_total_new[$v['id']] = $v['site_name'];
        }
        if (!empty($shopify_sales)) {
            foreach ($shopify_sales as $key => $value) {
                $advplatform = table('site')->where(['id' => $value['site_id']])->find();

                $wheregroup = array();
                $wheregroup[]  = ['a.updatetime', '>=', $end_time];
                $wheregroup['a.site_id'] = $value['site_id'];
                $wheregroup['a.type'] = '主运营';
                $site_log = table('site_log')
                    ->field("b.nickname")
                    ->alias('a')
                    ->join('qu_system_admin b', 'b.id = a.admin_id', 'left')
                    ->where($wheregroup)
                    ->find();
                if (!isset($site_log['nickname']) || empty($site_log['nickname'])) {
                    $site_log['nickname'] = '';
                }
                if (!empty($advplatform)) {
                    $site_name = $advplatform['site_name'];
                } else {
                    $site_name = '未知';
                }
                unset($site_total_new[$value['site_id']]);
                $zsales = (float)number_format($value['total'], 3, '.', '');
                $shopify_sales_remarks = '';
                if ($value['currency'] == 'EUR') {
                    $shopify_sales_remarks = '原销售额为€' . $zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_eur['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                if ($value['currency'] == 'MXN') {
                    $shopify_sales_remarks = '原销售额为Mex$' . $zsales;
                    $zsales = (float)number_format((float)$zsales * (float)$exchange_mxn['proportion'] / (float)$exchange['proportion'], 3, '.', '');
                }
                $zcount = (int)$value['count'];
                //时间段退款
                $sales_refund = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $value['site_id']])
                    ->sum('amount');
                $sales_refund = (float)number_format($sales_refund, 3, '.', '');
                //显示平台销售额
                $zadvcost_z2 = array();
                $advplat_arr = table('advplat')
                    ->where('site_id', $value['site_id'])
                    ->select()->toarray();
                $zadvcost_new = 0;
                $zadvcost_msg = array();
                if (!empty($advplat_arr)) {
                    foreach ($advplat_arr as $k0 => $v0) {
                        $zadvcost_z2 = table('advertising')
                            ->field('a.*,b.title')
                            ->alias('a')
                            ->join('qu_advplatform b','b.id = a.plat', 'left')
                            ->where($adv_where)
                            ->where('a.plat_account', $v0['id'])
                            ->where('a.status', 'normal')
                            ->select()->toarray();
                        if (!empty($zadvcost_z2)) {
                            foreach ($zadvcost_z2 as $k1 => $v1) {
                                if(isset($zadvcost_msg[$v1['title']])){
                                    $zadvcost_msg[$v1['title']] = $zadvcost_msg[$v1['title']] + (float)$v1['cost'];
                                }else{
                                    $zadvcost_msg[$v1['title']] = (float)$v1['cost'];
                                }
                                $zadvcost_new = (float)number_format((float)$zadvcost_new + (float)$v1['cost'], 3, '.', '');
                            }
                        }
                    }
                }
                $zadvcost_msg2 = '';
                if(!empty($zadvcost_msg)){
                    foreach ($zadvcost_msg as $kadmsg=>$vadmsg) {
                        if(!empty($zadvcost_msg2)){
                            $zadvcost_msg2 = $zadvcost_msg2 .','.$kadmsg.':'.$vadmsg;
                        }else{
                            $zadvcost_msg2 = $kadmsg.':'.$vadmsg;
                        }
                    }
                }
                
                $arr['adv_cost'] = (float)number_format((float)$zadvcost_new + (float)$arr['adv_cost'], 3, '.', '');
                if ($zsales > 0.02 && $zadvcost_new > 0.02) {
                    $roi = (float)number_format((float)$zsales / (float)$zadvcost_new, 3, '.', '');
                } else {
                    $roi = 0;
                }

                $value['freight'] = (float)number_format((float)$value['freight'] / (float)$exchange['proportion'], 3, '.', '');
                $value['material'] = (float)number_format((float)$value['material'] / (float)$exchange['proportion'], 3, '.', '');
                $gross_profit = (float)number_format((float)$zsales * 0.94 - (float)$value['freight'] - (float)$value['material'] - $zadvcost_new, 3, '.', '');

                //运营业绩
                //新规则 大店用渠道分 小店用运营分
            if($value['site_id'] == 121){//大店
                $remarks_operations = table('order')
                    ->field('sum(total_price) as total,sum(countnum) as count,tags,currency')
                    ->where($where)
                    ->where("site_id",$value['site_id'])
                    ->where($where_total_price)
                    ->group('tags')
                    ->order('total desc')
                    ->select()
                    ->toarray();
                if (!empty($remarks_operations)) {
                    foreach ($remarks_operations as $kr => $vr) {
                        
                        switch ($vr['tags']) {
                            case 'tt':
                                $remarks_operations[$kr]['nickname'] = 'TikTok';
                                break;
                            case 'fb':
                                $remarks_operations[$kr]['nickname'] = 'FB';
                                break;
                            case 'ggad':
                                $remarks_operations[$kr]['nickname'] = 'Google';
                                break;
                            case 'omnisend':
                                $remarks_operations[$kr]['nickname'] = '邮件';
                                break;
                            default:
                                $remarks_operations[$kr]['nickname'] = $vr['tags'];
                        }
                        $remarks_operations[$kr]['currency'] = '$';
                        $remarks_operations[$kr]['total'] = (float)number_format($remarks_operations[$kr]['total'], 3, '.', '');
                    }
                }else{
                    $remarks_operations = [];
                    $remarks_operations[0]['nickname'] = '暂无渠道';
                    $remarks_operations[0]['currency'] = '$';
                    $remarks_operations[0]['total'] = 0;
                }
            }else{
                $where_day  = array();
                $where_day[]  = ['time_stamp', '>=', $start_time];
                $where_day[]  = ['time_stamp', '<', $end_time];
                $where_day[]  = ['site_id', '=', $value['site_id']];
                $remarks_operations = table('shopify_personreport_day')
                    ->field('admin_id,sum(total_price) as total,sum(count) as counts,label_type,site_id,currency')
                    ->where($where_day)
                    ->group('admin_id')
                    ->order('total desc')
                    ->select()->toarray();
                if (!empty($remarks_operations)) {
                    foreach ($remarks_operations as $kr => $vr) {
                        $system_admin =  table('system_admin')
                            ->where('id', $vr['admin_id'])
                            ->find();
                        $remarks_operations[$kr]['nickname'] = $system_admin['nickname'];
                        switch ($vr['label_type']) {
                            case '1':
                                $remarks_operations[$kr]['label_type'] = '主运营';
                                break;
                            case '2':
                                $remarks_operations[$kr]['label_type'] = '副运营';
                                break;
                            default:
                                $remarks_operations[$kr]['label_type'] = '未知';
                        }
                        switch ($vr['currency']) {
                            case 'USD':
                                $remarks_operations[$kr]['currency'] = '$';
                                break;
                            case 'EUR':
                                $remarks_operations[$kr]['currency'] = '€';
                                break;
                            case 'MXN':
                                $remarks_operations[$kr]['currency'] = 'Mex$';
                                break;
                            default:
                                $remarks_operations[$kr]['currency'] = '未知';
                        }
                    }
                } else {
                    if (!empty($zsales)) {
                        $remarks_operations[0]['nickname'] = '暂无运营';
                        $remarks_operations[0]['currency'] = '$';
                        $remarks_operations[0]['total'] = $zsales;
                    }
                }
            }
                $shopify_sales_arr[] = [
                    'id' => $value['site_id'],
                    'name' => $site_name,
                    'gross_profit' => $gross_profit,
                    'count' => $zcount,
                    'sales' => $zsales,
                    'refund' => $sales_refund,
                    'nickname' => $site_log['nickname'],
                    'zadvcost_new' => $zadvcost_new,
                    'freight' => $value['freight'],
                    'material' => $value['material'],
                    'roi' => $roi,
                    'remarks' => $shopify_sales_remarks,
                    'remarks_operations' => $remarks_operations,
                    'zadvcost_msg2' => $zadvcost_msg2,
                ];
            }
        }
        if ($post['site_type'] == 0) {
            //未出单但有退款跟广告
            foreach ($site_total_new as $kst => $vst) {
                $remarks_operations3 = [];
                //时间段退款
                $sales_refund_st = table('order_refunds')
                    ->where($where_refund)
                    ->where(['site_id' => $kst])
                    ->sum('amount');
                $sales_refund_st = (float)number_format($sales_refund_st, 3, '.', '');
                if ($sales_refund_st >= 0.001) {
                    $remarks_operations2 = [];
                    $remarks_operations2['nickname'] = '没出单但有退款';
                    $remarks_operations2['currency'] = '';
                    $remarks_operations2['total'] = 0;
                    $remarks_operations3[] = $remarks_operations2;
                }
                $zadvcost_z2 = array();
                $advplat_arr = table('advplat')
                    ->where('site_id', $kst)
                    ->select()->toarray();
                if (!empty($advplat_arr)) {
                    foreach ($advplat_arr as $k0 => $v0) {
                        $zadvcost_z2 = table('advertising')
                            ->field('a.*,b.title')
                            ->alias('a')
                            ->join('qu_advplatform b','b.id = a.plat', 'left')
                            ->where($adv_where)
                            ->where('a.plat_account', $v0['id'])
                            ->where('a.status', 'normal')
                            ->select()->toarray();
                    }
                    $zadvcost_new = 0;
                    if (!empty($zadvcost_z2)) {
                        foreach ($zadvcost_z2 as $k1 => $v1) {
                            $zadvcost_msg[$v1['title']] = (float)$v1['cost'];
                            $zadvcost_new = (float)number_format((float)$zadvcost_new + $v1['cost'], 3, '.', '');
                        }
                    }
                    $zadvcost_msg2 = '';
                    if(!empty($zadvcost_msg)){
                        foreach ($zadvcost_msg as $kadmsg=>$vadmsg) {
                            if(!empty($zadvcost_msg2)){
                                $zadvcost_msg2 = $zadvcost_msg2 .','.$kadmsg.':'.$vadmsg;
                            }else{
                                $zadvcost_msg2 = $kadmsg.':'.$vadmsg;
                            }
                        }
                    }
                    if ($zadvcost_new >= 0.001) {
                        $remarks_operations2 = [];
                        $remarks_operations2['nickname'] = '没出单但有广告费';
                        $remarks_operations2['currency'] = '';
                        $remarks_operations2['total'] = 0;
                        $remarks_operations3[] = $remarks_operations2;
                        $arr['adv_cost'] = (float)number_format((float)$zadvcost_new + (float)$arr['adv_cost'], 3, '.', '');
                    }
                    if (!empty($remarks_operations3)) {
                        $shopify_sales_arr[] = [
                            'id' => $kst,
                            'name' => $vst,
                            'gross_profit' => 0,
                            'count' => 0,
                            'sales' => 0,
                            'refund' => $sales_refund_st,
                            'nickname' => '',
                            'zadvcost_new' => $zadvcost_new,
                            'roi' => 0,
                            'remarks_operations' => $remarks_operations3,
                            'zadvcost_msg2' => $zadvcost_msg2,
                        ];
                    }
                }
            }
        }

        //物流加成费
        $arr['gross_profit'] = (float)number_format((float)$arr['sales'] * 0.94 - (float)$arr['logistics'] - (float)$arr['purchase'] - (float)$arr['adv_cost'], 2, '.', '');
        $arr['roi'] = 0;
        if ($arr['adv_cost'] > 0.001 && $arr['sales'] > 0.001) {
            $arr['roi'] = number_format((float)$arr['sales'] / (float)$arr['adv_cost'], 3, '.', '');
        } //转化率ROI
        $sales_handle = '（美金$' . $arr['sales_usd'] . ',欧元€' . $arr['sales_eur'] . '）';
        $paid_handle = '（争议单' . $arr['dispute'] . ',退款单' . $arr['refund'] . ',授权状态订单' . $arr['authorized'] . '）';
        $gross_profit_handle = '（毛利' . $arr['gross_profit'] . '
        =销售额' . $arr['sales'] . '-物流' . $arr['logistics'] . '-采购' . $arr['purchase'] . '
        -广告' . $arr['adv_cost'] . '-手续费(6%)' . $arr['platform_discount'] . '）';
        $arr['gross_profit_handle1'] = '销售额-物流-采购-广告-手续费(6%)';
        $arr['gross_profit_handle2'] = $arr['sales'] . '-' . $arr['logistics'] . '-' . $arr['purchase'] . '-' . $arr['adv_cost'] . '-' . $arr['platform_discount'];
        $newarr = array();
        $newarr['arr'][] = $arr;
        $newarr['shopify_sales'] = $shopify_sales_arr;
        $newarr['sales_handle'] = $sales_handle;
        $newarr['paid_handle'] = $paid_handle;
        $newarr['gross_profit_handle'] = $gross_profit_handle;
        $newarr['start_time'] = $start_time;
        $newarr['end_time'] = $end_time;

        $filters[]  = $start_time_str;
        $filters[]  = $end_time_str;
        $sales_performance_list = $this->lists_news($filters);
        $newarr['sales_performance_list'] = $sales_performance_list;

        $redis->set('dashboard-shop-' . $start_time . '-' . $end_time . '-' . $post['day_changes'] . '-' . $post['site_type'], $newarr, 60 * 3);
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $newarr,
        ];
        return json($data);
    }


    /**
    * 方法详情
    * @param array params
    */
    public function lists_news($filters)
    {
         // 广告以及ROI
        $adv_where[]  = ['create_time', '>=', $filters[0]];
        $adv_where[]  = ['create_time', '<', $filters[1]];
        $where2[]  = ['a.created_at', '>=', strtotime($filters[0])];
        $where2[]  = ['a.created_at', '<=', strtotime($filters[1])];
        $where_total_price[] = ['a.financial_status', 'in', [DicOrder::$financial_status_partially_paid, DicOrder::$financial_status_paid, DicOrder::$financial_status_partially_refunded, DicOrder::$financial_status_refunded]];
        $lists = table('order')
            ->field('sum(a.total_price) as total_price,currency,b.tag_source,b.tag_campaign')
            ->alias('a')
            ->join('qu_customerjourney b','b.order_number = a.order_number', 'left')
            ->where('a.site_id','121')
            ->where($where_total_price)
            ->where($where2)
            ->group('b.tag_source,b.tag_campaign')
            ->order('b.tag_source desc,b.tag_campaign desc')
            ->select()
            ->toArray();
        $Customerjourney = new \app\admin\controller\Customerjourney($this->app);
        $lists_news = array();
        if(!empty($lists)){
            //整合成三维数组
            $groupedStatistics = [];
            foreach ($lists as $item) {
                // 广告以及ROI
                $admin_id = $Customerjourney->tag_change($item['tag_campaign'], 3);
                $advcosts = 0;
                if(!empty($admin_id)){
                    $where_admin['admin_id'] = $admin_id;
                    $advcost = table('advertising')
                        ->field('sum(cost) as cost')
                        ->where($adv_where)
                        ->where('status', 'normal')
                        ->where($where_admin)
                        ->find();
                    if (!empty($advcost['cost'])) {
                        $advcosts = number_format($advcost['cost'], 3, '.', '');
                    }
                }

                $tagSource = $item["tag_source"];
                $totalPrice = $item["total_price"];
                if (!empty($tagSource) && is_numeric($totalPrice)) {
                    if (!array_key_exists($tagSource, $groupedStatistics)) {
                        $groupedStatistics[$tagSource] = ["advcost_sum" => 0,"total_price_sum" => 0, "info" => []];
                    }
                    $groupedStatistics[$tagSource]["total_price_sum"] += $totalPrice;
                    $groupedStatistics[$tagSource]["advcost_sum"] += $advcosts;
                    if (!in_array($tagSource, $groupedStatistics[$tagSource]["info"])) {
                        $item['advcost'] = $advcosts;
                        $groupedStatistics[$tagSource]["info"][] = $item;
                    }
                }
            }
            //统计
            foreach ($groupedStatistics as $k => $v) {
                $tag_source = $Customerjourney->tag_change($k, 1);
                foreach ($v['info'] as $key => $val) {
                    $tag_campaign = $Customerjourney->tag_change($val['tag_campaign'], 2);
                    //ROI
                    if ($val['advcost'] > 0.001 && $val['total_price'] > 0.001) {
                        $roi = number_format((float)$val['total_price'] / (float)$val['advcost'], 3, '.', '');
                    }else{
                        $roi = 0;
                    }

                    $lists_new = array(
                        'total_price' => number_format((float)$val['total_price']*1, 2, '.', ''),
                        'currency' => $val['currency'],
                        'tag_source' => $Customerjourney->tag_change($val['tag_source'], 1),
                        'advcost' => $val['advcost'],
                        'roi' => $roi,
                        'tag_campaign' => $tag_campaign
                    );
                    $lists_news[] = $lists_new;
                }
                $lists_new = array(
                    'total_price' => number_format((float)$v['total_price_sum']*1, 2, '.', ''),
                    'currency' => "",
                    'roi' => "",
                    'tag_source' => $tag_source,
                    'advcost' => number_format((float)$v['advcost_sum']*1, 2, '.', ''),
                    'tag_campaign' => "统计"
                );
                $lists_news[] = $lists_new;
            }
        }
        return $lists_news;
    }

    //客服接口数据修改
    public function   kfinput()
    {
        // $kf_data_insert = table('kfdetail')->where(['tid' => 1, 'did' => 1, 'orderid' => 'dsffs'])->find();
        // if (empty($kf_data_insert)) {
        //     return 2;
        // }
        // return 3;
        // halt($this->kfdetail('罩杯偏小,不合身,款式与宣传不符'));
        $data = Excel::import('storage/wz.xlsx');
        unset($data[1]);
        halt($data);
        //查询问题详情和问题类型表
        $qustiondetail_title = table('qustiondetail')->select()->toarray();
        $qustiondetail_title = array_column($qustiondetail_title, 'id', 'title');
        $qustiondetail_id = table('qustiondetail')->select()->toarray();
        $qustiondetail_id = array_column($qustiondetail_id, 'pid', 'id');
        foreach ($data as $value) {
            //如果物流单号和问题详情都不为空才执行相关操作
            //订单号
            $kd_num = trim($value[2]);
            //问题详情
            $qusdetail = trim($value[5]);
            $email_content = trim($value[6]);
            if (!empty($kd_num) && !empty($qusdetail)) {
                //$value[2]快递单号  #value[5]   为问题详情  查询标记表  没有记录则插入
                //通过快递单号插入订单号
                $order = table('order')->field('id')->where('tracking_number', $kd_num)->find();
                if (!empty($order)) {
                    //更新相应的值is_mark,mark_time的值
                    table('order')->where('id', $order['id'])->update(['is_mark' => 1, 'mark_time' => time(), 'email_detail' => $email_content]);
                    //处理问题详情
                    $qustion_detail = explode(',', $qusdetail);
                    foreach ($qustion_detail as  $value) {
                        $insert_arr = [
                            'did' => !empty($qustiondetail_title[$value]) ? $qustiondetail_title[$value] : 0,
                            'tid' => !empty($qustiondetail_id[$qustiondetail_title[$value]]) ? $qustiondetail_id[$qustiondetail_title[$value]] : 0,
                            'orderid' => !empty($order['id']) ? $order['id'] : 0,
                        ];
                        $kf_data_insert = table('kfdetail')->where(['tid' => $insert_arr['tid'], 'did' => $insert_arr['did'], 'orderid' => $insert_arr['orderid']])->find();
                        if (empty($kf_data_insert)) {
                            table('kfdetail')->insert($insert_arr);
                        }
                    }
                }
                file_put_contents('kefu.txt', $kd_num);
            }
        }
        return success('操作成功');
    }
}
